package com.kdx.wallet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kdx.wallet.entity.Prod;
import com.kdx.wallet.entity.Record;
import com.kdx.wallet.entity.Wallet;
import com.kdx.wallet.mapper.ProdMapper;
import com.kdx.wallet.mapper.RecordMapper;
import com.kdx.wallet.mapper.WalletMapper;
import com.kdx.wallet.service.ProdService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService {
    @Resource
    private WalletMapper walletMapper;
    @Resource
    private RecordMapper recordMapper;
    @Resource
    private ProdMapper prodMapper;

    /**
     * 购买商品
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean buyProd(Integer userId, Integer prodId) {
        Wallet wallet = user4wallet(userId);
        Prod prod = prodMapper.selectById(prodId);

        wallet.setBalance(wallet.getBalance() - prod.getProdPrice());
        int a = walletMapper.updateById(wallet);

        Record record = new Record();
        record.setUserId(wallet.getUserId());
        record.setType(1);
        record.setAmount(prod.getProdPrice());
        record.setProdId(prodId);
        int insert = recordMapper.insert(record);

        return a > 0 && (insert > 0);
    }

    /**
     * 申请退款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean requestRefund(Integer userId, Integer prodId) {
        Wallet wallet = user4wallet(userId);
        Prod prod = prodMapper.selectById(prodId);

        wallet.setBalance(wallet.getBalance() + prod.getProdPrice());
        int a = walletMapper.updateById(wallet);

        Record record = new Record();
        record.setUserId(wallet.getUserId());
        record.setType(2);
        record.setAmount(prod.getProdPrice());
        record.setProdId(prodId);
        int insert = recordMapper.insert(record);

        return a > 0 && (insert > 0);
    }

    /**
     * 根据userId查找wallet
     */
    private Wallet user4wallet(Integer userId) {
        QueryWrapper<Wallet> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return walletMapper.selectOne(wrapper);
    }
}
